import { useCacheRequest } from '../plugins/useRequest.js';

function trigger(ctx, args, state, data, options) {
  let { predicate, action } = options;
  if (typeof predicate !== 'function') {
    predicate = (state, data, args) => data !== undefined;
  }
  let cancel = predicate.call(ctx, state, data, args);
  if (cancel !== false && typeof action === 'function') {
    action.apply(ctx, args);
  }
}

export function useAutoGetter(options) {
  /*
   * options: {
   *   // 原始 getter
   *   getter: (Function) state => state.data,
   *   // 什么情况下触发 action
   *   predicate: (Function) (state, data) => Boolean,
   *   // getter 对应的需要触发的 action,
   *   action: (Function) function (args) { this.action(args) },
   * }
   * */
  options = Object.assign({}, options);
  return function (state) {
    options.ctx = this;
    options.data = options.getter.call(this, state);
    if (typeof options.data === 'function') {
      return function () {
        let args = [].slice.apply(arguments);
        let res = options.data.apply(options.ctx, args);
        trigger(options.ctx, args, state, res, options);
        return res;
      };
    } else {
      trigger(options.ctx, undefined, state, options.data, options);
      return options.data;
    }
  };
}
export function useAutoAction(options) {
  /*
   * options: {
   *   action: (Function) async () => {}, 原始的 action,一定要把数据 return 出来
   *   options: (Object) {}, 其他传递给 useRequest 的 options...
   * */
  options = Object.assign({}, options);
  return async function (params) {
    let _options = Object.assign({}, options.options, { context: this });
    return await useCacheRequest(options.action, params, _options);
  };
}
